package com.lg.head_first.chap02.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * 一个气象公告类，当气象 温度 等气象信息 发生改变时  通知各大订阅者
 *
 * @author by Mr. Li 2020/7/31 14:59
 */
public class WeatherData implements Subject {

    private final List<Observer> observers;
    private float temperature;
    private float humidity;
    private float pressure;

    public WeatherData() {
        this.observers = new ArrayList<>();
    }

    /**
     * 一旦气象测量更新，此方法会被调用
     */
    public void measurementsChanged() {
        notifyObserver();
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        int i = observers.indexOf(observer);
        if (i >= 0) {
            observers.remove(i);
        }
    }

    @Override
    public void notifyObserver() {
        if (observers.size() > 0) {
            for (Observer observer : observers) {
                observer.update(temperature, humidity, pressure);
            }
        }
    }

    /**
     * 温度
     */
    public float getTemperature() {
        // do something
        return temperature;
    }

    /**
     * 湿度
     */
    public float getHumidity() {
        // do something
        return humidity;
    }

    /**
     * 气压
     */
    public float getPressure() {
        // do something
        return pressure;
    }

    public void setMeasurements(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }
}
